<?php
/**
 * Database Twibs
 * @author	Jeremy Lindblom
 */

namespace db;

// Connection Singleton
function c(){static$m=0;$m=(!$m)?@new \mysqli(\c('dbh'),\c('dbu'),\c('dbp'),\c('dbn')):$m;if($m->connect_error)\e(3);return$m;}

// Select
function s($c,$w=0){$a=array();$r=q(1,$c,$w);while($r&&$o=$r->fetch_object($c))$a[]=$o;return$a;}

// Insert
function i($c,$a){\array_walk($a,'db\v');return q(2,$c,'(`'.\join('`,`',\array_keys($a=(array)$a)).'`)VALUES('.\join(',',$a).')');}

// Update
function u($c,$a,$i){\array_walk($a,'db\v','`%s`=');return q(3,$c,\join(',',(array)$a)." WHERE id=$i");}

// Delete
function d($c,$i=0){return q(4,$c,'WHERE '.(is_int($i)?(!$i?'1':"id=$i"):$i));}

// Select Row by ID
function r($c,$i){$i=(int)$i;return($o=q(1,$c,"WHERE id=$i")->fetch_object($c))?$o:e($c);}

// Get Empty Row
function e($c){$o=new$c;$r=q(0,$c);while($f=$r->fetch_row())$o->$f[0]=NULL;return$o;}

// SQL Query Type
function t($s,$t){$a=array("SHOW COLUMNS FROM $t","SELECT $t.* FROM $t","INSERT INTO $t","UPDATE $t SET","DELETE FROM $t");return$a[$s];}

// Prepare a Value
function v(&$v,$k=0,$p=0){return$v=($p?\sprintf($p,$k):'').(\is_numeric($v)?$v:(\is_null($v)?'NULL':'"'.\addslashes($v).'"'));}

// Format a Join
function j($t0,$t1,$f=1){return"INNER JOIN $t1 ON ".($f?"$t0.id=$t1.{$t0}_id ":"$t0.{$t1}_id=$t1.id ");}

// Get Glue Table
function g($t0,$t1=0){$t0=\get_class($t0)?:$t0;$t1=\get_class($t1)?:$t1;$g=array($t0,$t1);\sort($g);return array(\join('_to_',$g),$t0,$t1);}

// Query Cache
/* Operations:
$q=0,$o=0			clear cache
$q=$str,$o=0		get cached result
$q=$str,$o=1||$obj	set cached result
$q=1,$o=0			return cache array
*/
function h($q=0,$o=0){static$a=array();return$o?($a[$q]=$o):(\is_string($q)?@$a[$q]:($q?$a:\array_walk($a,function(&$v){$v=0;})));}

// Perform Query
function q($s,$c=0,$w=0){$r=h($q=!$c?$s:t($s,$c).($w?" $w":''))?:h($q,c()->query($q));if($q[0]!='S')h();return$r;}

// Relationship Queries
function belongs_to($t,$f,$o){$fk=$t.'_id';return r($f,$o->$fk);}
function has_one($t,$f,$o){return\is_array($r=s($f,"WHERE {$t}_id={$o->id}"))?$r[0]:$r;}
function has_many($t,$f,$o){return s($f,"WHERE {$t}_id={$o->id}");}
function many_to_many($t,$f,$o){list($g,,)=g($t,$f);return s($f,j($f,$g).j($g,$t,0)."WHERE $t.id={$o->id}");}

// Query Debugging
if(\defined('DEBUG'))\register_shutdown_function(function(){echo'<strong>Queries</strong>:<pre>'.\print_r(\array_keys(h(1)),1).'</pre>';});